<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use FormBuilder\Factory\Elm;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserAgent;
use plugin\ycMassage\app\model\MassageUserAgentApply;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\notice\Notice;
use support\Request;
use think\facade\Db;

class AgentApplyController extends BaseController
{
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addRightButton('examine', '审核', [
            'api'    => $this->pluginPrefix . '/admin/AgentApply/examine',
            'path' => '/AgentApply/examine',
            'type'      => 'modal',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => 0
            ]
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addScreen('keywords', 'input', '搜索', [
            'placeholder' => '姓名、手机号搜索'
        ]);
        $builder->addScreen('examine', 'select', '审核状态', [
            'options' => Examine::getOptions()
        ]);
        $builder->addScreen('regions', 'input', '地区', [
            'placeholder' => '地区模糊搜索'
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumn('name', '姓名', [
                'width' => 120,
            ])
            ->addColumn('mobile', '手机号', [
                'width' => 120,
            ])
            ->addColumn('uid', 'UID', [
                'width' => 120,
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120,
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('agent_level', '意向代理等级', [
                'width' => 140
            ])
            ->addColumn('province', '意向代理省', [
                'width' => 120,
            ])
            ->addColumn('city', '意向代理市', [
                'width' => 120,
            ])
            ->addColumn('area', '意向代理区', [
                'width' => 120,
            ])
            ->addColumnEle('examine', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style')
                ],
            ])
            ->addColumn('message', '审核结果', [
                'minWidth' => 120,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['a.saas_appid', '=', $request->saas_appid]
        ];
        $keywords = $request->get('keywords');
        if ($keywords) {
            $where[] = ['a.name|a.mobile', 'like', "%{$keywords}%"];
        }
        $regions = $request->get('regions');
        if ($regions) {
            $where[] = ['a.province|a.city|a.area', 'like', "%{$regions}%"];
        }
        $examine = $request->get('examine');
        if ($examine !== null) {
            $where[] = ['a.examine', '=', $examine];
        }
        $data = MassageUserAgentApply::where($where)
            ->alias('a')
            ->join('massage_user u', 'u.id=a.uid', 'LEFT')
            ->order('a.create_time desc')
            ->field('a.*,u.nickname,u.headimg')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->uid) {
                    $item->nickname = base64_decode($item->nickname);
                    if (strpos($item->headimg, 'http') !== 0) {
                        $item->headimg = UploadService::url($item->headimg);
                    }
                }
            });
        return $this->successRes($data);
    }
    public function examine(Request $request)
    {
        $id = $request->get('id');
        $MassageUserAgentApply = MassageUserAgentApply::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageUserAgentApply) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $MassageUserAgentApply->examine = $D['examine'];
            Db::startTrans();
            try {
                if (!in_array($MassageUserAgentApply->examine, [Examine::YES['value'], Examine::NO['value']])) {
                    throw new \Exception('请选择审核状态');
                }
                $notice = new Notice();
                if ($MassageUserAgentApply->uid) {
                    $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageUserAgentApply->uid])
                        ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                        ->field('u.id,u.nickname,u.mobile,uw.openid')
                        ->find();
                    if (!$MassageUser) {
                        throw new \Exception('用户不存在');
                    }
                } else {
                    $MassageUser = MassageUser::alias('u')->where(['u.mobile' => $MassageUserAgentApply->mobile, 'u.saas_appid' => $MassageUserAgentApply->saas_appid])
                        ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                        ->field('u.id,u.nickname,u.mobile,uw.openid')
                        ->find();
                    if (!$MassageUser) {
                        $MassageUser = new MassageUser;
                        $MassageUser->saas_appid = $MassageUserAgentApply->saas_appid;
                        $MassageUser->mobile = $MassageUserAgentApply->mobile;
                        $MassageUser->nickname = $MassageUserAgentApply['name'];
                        $MassageUser->headimg = getHpConfig('default_avatar', $MassageUserAgentApply->saas_appid, 'user');
                        $MassageUser->save();
                    }
                }
                $notice->addUSER($MassageUser->mobile, $MassageUser->openid);
                $notice->saas_appid = $MassageUserAgentApply->saas_appid;
                $notice->type = NoticeType::EXAMINE['value'];
                $notice->role = ['TECHNICIAN'];
                if ($MassageUserAgentApply->examine == Examine::NO['value']) {
                    if (empty($D['message'])) {
                        throw new \Exception('请填写驳回理由');
                    }
                    $notice->setData([
                        'type' => '代理申请',
                        'state' => '已驳回',
                        'result' => $D['message'],
                        'trade' => $MassageUserAgentApply->id,
                        'time' => date('Y-m-d H:i:s')
                    ]);
                    $MassageUserAgentApply->message = $D['message'];
                } else {
                    $unique_agent = getHpConfig('unique_agent', $MassageUserAgentApply->saas_appid, 'agent');
                    if ($unique_agent) {
                        $where = [
                            'province_id' => $MassageUserAgentApply->province_id,
                            'city_id' => $MassageUserAgentApply->city_id,
                            'area_id' => $MassageUserAgentApply->area_id
                        ];
                        $MassageUserAgent = MassageUserAgent::where($where)->find();
                        if ($MassageUserAgent) {
                            throw new \Exception('该地区已有代理');
                        }
                    }
                    $notice->setData([
                        'type' => '代理申请',
                        'state' => '已通过',
                        'result' => '恭喜您，您的代理申请已通过',
                        'trade' => $MassageUserAgentApply->id,
                        'time' => date('Y-m-d H:i:s')
                    ]);
                    $MassageUserAgentApply->message = '通过';
                    $where = [
                        'uid' => $MassageUser->id,
                        'province_id' => $MassageUserAgentApply->province_id,
                        'city_id' => $MassageUserAgentApply->city_id,
                        'area_id' => $MassageUserAgentApply->area_id
                    ];
                    $MassageUserAgent = MassageUserAgent::where($where)->find();
                    if (!$MassageUserAgent) {
                        $MassageUserAgent = new MassageUserAgent();
                        $MassageUserAgent->saas_appid = $MassageUserAgentApply->saas_appid;
                        $MassageUserAgent->uid = $MassageUser->id;
                    }
                    $MassageUserAgent->name = $MassageUserAgentApply->name;
                    $MassageUserAgent->mobile = $MassageUserAgentApply->mobile;
                    $MassageUserAgent->province_id = $MassageUserAgentApply->province_id;
                    $MassageUserAgent->province = $MassageUserAgentApply->province;
                    $MassageUserAgent->city_id = $MassageUserAgentApply->city_id;
                    $MassageUserAgent->city = $MassageUserAgentApply->city;
                    $MassageUserAgent->area_id = $MassageUserAgentApply->area_id;
                    $MassageUserAgent->area = $MassageUserAgentApply->area;
                    $MassageUserAgent->state = State::YES['value'];
                    if (!empty($D['expire_time']) && $D['expire_time'] > date('Y-m-d H:i:s')) {
                        $MassageUserAgent->expire_time = $D['expire_time'] . ' 23:59:59';
                    }
                    if (!empty($D['commission'])) {
                        $MassageUserAgent->commission = $D['commission'];
                    }
                    $MassageUserAgent->save();
                    if ($D['cancel_sub'] == State::YES['value']) {
                        if (!$MassageUserAgent->province_id) {
                            # 总代理，将除了当前用户的其他代理设置为无效
                            MassageUserAgent::where(['uid' => $MassageUser->id])
                                ->where('id', '<>', $MassageUserAgent->id)
                                ->update(['state' => State::NO['value'], 'message' => '升级总代理，取消其他代理']);
                        } elseif ($MassageUserAgent->province_id && !$MassageUserAgentApply->city_id) {
                            # 省代理，将除了当前用户的其他省代理设置为无效
                            MassageUserAgent::where(['uid' => $MassageUser->id, 'province_id' => $MassageUserAgent->province_id])
                                ->where('id', '<>', $MassageUserAgent->id)
                                ->update(['state' => State::NO['value'], 'message' => '升级省代理，取消当前省份下其他代理']);
                        } elseif ($MassageUserAgentApply->city_id && !$MassageUserAgentApply->area_id) {
                            # 市代理，将除了当前用户的其他市代理设置为无效
                            MassageUserAgent::where(['uid' => $MassageUser->id, 'city_id' => $MassageUserAgent->city_id])
                                ->where('id', '<>', $MassageUserAgent->id)
                                ->update(['state' => State::NO['value'], 'message' => '升级市代理，取消当前城市下其他代理']);
                        }
                    }
                }
                $MassageUserAgentApply->save();
                $notice->send();
                Db::commit();
                return $this->success('审核成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('name', 'info', '姓名', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('mobile', 'info', '手机号', '', [
            'col'           => 18,
        ]);
        $builder->addComponent('agent_level', 'info', '意向代理等级', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('province', 'info', '省', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('city', 'info', '市', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('area', 'info', '区', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('审核');
        $builder->addRow('cancel_sub', 'radio', '取消下级代理', State::YES['value'], [
            'col' => 12,
            'prompt' => [
                'text' => "总代理：取消除了当前用户的其他代理\n省代理：取消当前省份下其他代理\n市代理：取消当前城市下其他代理",
            ],
            'options' => [
                [
                    'value' => State::YES['value'],
                    'label' => '取消'
                ],
                [
                    'value' => State::NO['value'],
                    'label' => '不取消'
                ]
            ]
        ]);
        $builder->addRow('examine', 'radio', '状态', Examine::YES['value'], [
            'col' => 12,
            'options' => Examine::getOptions(),
            'control' => [
                [
                    'value' => Examine::NO['value'],
                    'where' => '==',
                    'rule' => [
                        Elm::textarea('message', '驳回理由')
                            ->col([
                                'span' => 24
                            ])
                            ->props([
                                'filterable' => true,
                                'placeholder' => '请输入驳回理由',
                            ])
                    ],
                ],
            ]
        ]);
        $builder->addRow('expire_time', 'date', '到期时间', '', [
            'col' => 12,
            'props' => [
                'type' => 'date',
                'format' => 'YYYY-MM-DD',
                'value-format' => 'YYYY-MM-DD',
                'clearable' => true,
                'placeholder' => '请选择时间',
            ]
        ]);
        $builder->addRow('commission', 'number', '独立分成比例', '', [
            'col' => 12,
            'props' => [
                'prompt' => [
                    'text' => '佣金比例为0-100之间的整数，如设置为10，则代理佣金为订单金额的10%，0或不填：使用系统设置',
                ],
                'props' => [
                    'min' => 0,
                    'max' => 100,
                    'precision' => 0,
                ]
            ]
        ]);
        $data = $builder->setData($MassageUserAgentApply)->create();
        return $this->successRes($data);
    }
}
